﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Orpheus.Analyzer
{
    public class TimeStepFunction<TOutputValue>
    {
        private readonly Dictionary<TimeInterval, TOutputValue> _intervalValues;

        public IList<TimeInterval> Intervals
        {
            get { return _intervalValues.Keys.ToList(); }
        }

        public TimeStepFunction()
        {
            _intervalValues = new Dictionary<TimeInterval, TOutputValue>(new TimeIntervalEqualityComparer());
        }

        public TOutputValue GetValue(TimeSpan time)
        {
            var valueInterval =
                _intervalValues.SingleOrDefault(
                    intervalValue => time >= intervalValue.Key.Start && time < intervalValue.Key.End);

            if (valueInterval.Key == null)
            {
                throw new ArgumentOutOfRangeException("time");
            }

            return valueInterval.Value;
        }

        public void SetValueForInterval(TOutputValue value, TimeInterval interval)
        {
            if (interval == null)
            {
                throw new ArgumentNullException("interval");
            }

            if (!_intervalValues.ContainsKey(interval))
            {
                _intervalValues.Add(interval, value);
            }
            else
            {
                _intervalValues[interval] = value;
            }
        }

        public void ExcludeInterval(TimeInterval interval)
        {
            if (_intervalValues.ContainsKey(interval))
            {
                _intervalValues.Remove(interval);
            }
        }
    }
}
